﻿using System;
using System.Collections.Generic;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;
using QingShan.DependencyInjection;
using QingShan.Core.FreeSql;
using QingShan.Data;
using FreeSql;
using Mapster;
using QingShan.Utilities;

using @Model.ContractNamespace;
using @Model.DtoNamespace;
using @Model.EntityNamespace;
namespace @Model.Namespace
{
    /// <summary>
	/// @Model.Remark
    /// </summary>
    public class @(Model.Name)Service:I@(Model.Name)Contract,IScopeDependency
    {
        private readonly IRepository<@Model.TableName> _@(Model.FullName)Repository;
        public @(Model.Name)Service(IRepository<@Model.TableName> @(Model.FullName)Repository)
        {
            _@(Model.FullName)Repository = @(Model.FullName)Repository;
        }

        /// <summary>
        /// 获取数据
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        public async Task<PageOutputDto<@(Model.Name)OutputDto>> PageAsync(Page@(Model.Name)InputDto dto)
        {
            return await _@(Model.FullName)Repository.Select.ToPageResultAsync<@Model.TableName,@(Model.Name)OutputDto>(dto,null);
        }

        /// <summary>
        /// 添加
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<StatusResult> AddAsync(@(Model.Name)InputDto input)
        {
            var entity = input.Adapt<@(Model.TableName)>();
            entity.Id = Snowflake.GenId();
            var result = await _@(Model.FullName)Repository.InsertAsync(entity);
            return new StatusResult(result == null, "添加失败");
        }

        /// <summary>
        /// 修改用户
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<StatusResult> UpdateAsync(@(Model.Name)InputDto input)
        {
            var data = await _@(Model.FullName)Repository.Select.Where(o => o.Id == input.Id).FirstAsync();
            if (data == null)
            {
                return new StatusResult("数据不存在！");
            }
            @foreach (var item in Model.ColumnConfig)
            {
                if (!(item.PropName == "CreateTime"||item.PropName == "DeleteTime"||item.PropName == "CreatedId"||item.PropName == "Id"))
                {
            <text>
            data.@(item.PropName) = input.@(item.PropName);
            </text>
                }
            }
            int res = await _@(Model.FullName)Repository.UpdateAsync(data);
            return new StatusResult(res == 0, "修改失败");
        }

        /// <summary>
        /// 删除角色
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<StatusResult> DeleteAsync(string id)
        {
            var res = await _@(Model.FullName)Repository.DeleteAsync(id);
            return new StatusResult(res == 0, "删除失败");
        }

    }
}
